package com.zeny.coding.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zeny.coding.dto.CourseContentDto;
import com.zeny.coding.dto.PageDto;
import com.zeny.coding.entity.CourseContent;
import com.zeny.coding.entity.CourseContentExample;
import com.zeny.coding.mapper.CourseContentMapper;
import com.zeny.coding.service.CourseContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <h2>课程-内容服务</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
@Service
public class CourseContentServiceImpl implements CourseContentService {

    @Autowired
    private CourseContentMapper courseContentMapper;

    @Override
    public void list(PageDto<CourseContentDto> pageDto) {
        //分页
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        //设置条件
        CourseContentExample courseContentExample = new CourseContentExample();
        courseContentExample.setOrderByClause("id desc");
        //查询结果
        List<CourseContent> courseContentList = this.courseContentMapper.selectByExample(courseContentExample);
        PageInfo<CourseContent> pageInfo = new PageInfo<>(courseContentList);
        //设置总条数
        pageDto.setTotal(pageInfo.getTotal());
        //封装成DTO传输
        List<CourseContentDto> courseContentDtoList = new ArrayList<>();
        for (CourseContent courseContent : courseContentList) {
            CourseContentDto courseContentDto = new CourseContentDto();
            BeanUtils.copyProperties(courseContent, courseContentDto);
            courseContentDtoList.add(courseContentDto);
        }
        //设置记录数
        pageDto.setList(courseContentDtoList);
    }

    @Transactional
    @Override
    public void save(CourseContentDto courseContentDto) {
        //DTO转~
        CourseContent courseContent = new CourseContent();
        BeanUtils.copyProperties(courseContentDto, courseContent);
        int count = this.courseContentMapper.updateByPrimaryKeyWithBLOBs(courseContent);
        if (count == 0) {
            //没有更新成功,说明还没插入过,那就新增
            this.courseContentMapper.insertSelective(courseContent);
        }
    }


    @Override
    public CourseContentDto findById(String id) {
        CourseContent courseContent = this.courseContentMapper.selectByPrimaryKey(id);
        CourseContentDto courseContentDto = new CourseContentDto();
        if (courseContent != null) {
            BeanUtils.copyProperties(courseContent, courseContentDto);
        }
        return courseContentDto;
    }

    @Transactional
    @Override
    public void deleteById(String id) {
        this.courseContentMapper.deleteByPrimaryKey(id);
    }
}
